package com.flushbonading.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.flushbonading.util.TokenUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zyx 2134208960@qq.com
 * @author zk
 * @version 0.1.0
 * @date 2021-03-16 11:21
 * @date 2021-09-01
 * @since 0.1.0
 **/

public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
        final String token = request.getHeader("token");
        final String user_id = JWT.decode(token).getAudience().get(0);
        System.out.println(user_id + "用户进入了拦截器");
        System.out.println(request.getRequestURI());
        final Map<String, Object> map = new HashMap<>();
        try {
            //检查token合法性
            TokenUtils.verify(token);
            return true;
        } catch (final SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg", "签名无效");
        } catch (final TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg", "token过期");
        } catch (final Exception e) {
            e.printStackTrace();
            map.put("msg", "token无效");
        }
        map.put("state", false);
        final String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        return false;
    }

    @Override
    public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) throws Exception {

    }
}
